package com.wetao.lib_common.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PathEffect;
import android.graphics.Point;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.graphics.Rect;
import android.graphics.Region;
import android.graphics.drawable.NinePatchDrawable;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.View;

import com.wetao.lib_common.R;
import com.wetao.lib_common.utils.ComUtil;
import com.wetao.lib_common.utils.LogUtils;

import java.util.ArrayList;
import java.util.Collections;

/**
 * 折线图View
 */
public class LineChartView extends View {
    private static final String TAG = "LineChartView";

    //Y轴  每个刻度的间距间距
    private int myInterval;
    //X轴  每个刻度的间距间距
    private int mxInterval;
    //Y轴距离view长度
    private int mLeftInterval;
    //y轴距离view的初始长度
    private int initLeftInterval;
    //y轴距离view右边长度
    private int mRightInterval;
    //X轴距离view长度
    private int mBottomInterval;
    //X轴距离view顶部长度
    private int mTopInterval;
    //Y轴字体的大小
    private float mYAxisFontSize;
    //View 的宽和高
    private int mWidth, mHeight;
    //线的颜色
    private int mLineColor;
    //线条的宽度
    private float mStrokeWidth = 2.0f;
    //y轴刻度线
    private int myLineNum = 11;
    //X轴的文字
    private ArrayList<String> mXAxis;
    //标签
    private ArrayList<String> mLabels;
    //点 (温度)
    private ArrayList<ArrayList<Float>> mYAxisList;
    //纵轴最大值
    private int maxYValue;
    //纵轴分割数量
    private int dividerCount;
    //画坐标线的轴
    private Paint axisPaint;
    //画y轴数据
    private Paint numPaint;
    //画X轴文字
    private Paint axisTextPaint;
    //画y轴文字
    private Paint yTextPaint;
    //y轴文字rect
    private Rect yTextRect = new Rect();
    //x轴开始绘制的位置
    private int startDrawX = 0;
    //标签间隔
    private int mLabelInterval = 60;
    //连接线条
    private Paint linePaint;
    //小圆点内环
    private Paint innerCirclePaint;
    //折线路径
    private Path mpolylinePath;
    //小圆点外环半径
    private int outerRadius;
    //颜色
    private int[] colorArray = {

            Color.parseColor("#FF00A8B2"), //红色
            Color.parseColor("#FFFF3A51")//绿色
    };
    //向上向下
    private int[] direct = { 1,-1};

    public LineChartView(Context context) {
        this(context, null);
        init(context);
    }

    public LineChartView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
        init(context);
    }

    public LineChartView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        /**
         * 获得我们所定义的自定义样式属性
         */
        TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.LineChartView, defStyleAttr, 0);
        // 折线颜色
        mLineColor = a.getColor(R.styleable.LineChartView_lineChartColor, Color.BLACK);
        // X轴每个刻度的间距间距
        dividerCount = a.getInt(R.styleable.LineChartView_dividerCount, 10);
        // X轴每个刻度的间距间距
        mxInterval = a.getDimensionPixelSize(R.styleable.LineChartView_xInterval, (int) TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP, 32, getResources().getDisplayMetrics()));
        // Y轴距离view长度 初始设置
        initLeftInterval = a.getDimensionPixelSize(R.styleable.LineChartView_leftInterval, (int) TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP, 16, getResources().getDisplayMetrics()));
        mRightInterval = a.getDimensionPixelSize(R.styleable.LineChartView_rightInterval, (int) TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP, 16, getResources().getDisplayMetrics()));
        // X轴距离view底部的高度
        mBottomInterval = a.getDimensionPixelSize(R.styleable.LineChartView_bottomInterval, (int) TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP, 16, getResources().getDisplayMetrics()));
        // X轴距离view顶部长度
        mTopInterval = a.getDimensionPixelSize(R.styleable.LineChartView_topInterval, (int) TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP, 16, getResources().getDisplayMetrics()));
        // Y轴字体的大小
        // 默认设置为16sp，TypeValue也可以把sp转化为px
        mYAxisFontSize = a.getDimensionPixelSize(R.styleable.LineChartView_yAxisFontSize, (int) TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_SP, 10, getResources().getDisplayMetrics()));

        a.recycle();
    }

    private void init(Context context) {
        // 画坐标线的轴
        axisPaint = new Paint();
        axisPaint.setAntiAlias(true);
        axisPaint.setTextSize(mYAxisFontSize);
        axisPaint.setColor(Color.parseColor("#D9D9D9"));

        numPaint = new Paint();
        numPaint.setAntiAlias(true);
        numPaint.setTextSize(mYAxisFontSize);
        numPaint.setColor(Color.parseColor("#D9D9D9"));

        // 画X轴文字
        axisTextPaint = new Paint();
        axisTextPaint.setAntiAlias(true);
        axisTextPaint.setStyle(Paint.Style.FILL);
        axisTextPaint.setTextSize(mYAxisFontSize);
        axisTextPaint.setColor(Color.parseColor("#878787"));

        yTextPaint = new Paint();
        yTextPaint.setAntiAlias(true);
        yTextPaint.setTextSize(ComUtil.sp2px(getContext(), 10));
        yTextPaint.setTextAlign(Paint.Align.CENTER);
        yTextPaint.setStyle(Paint.Style.FILL);
        yTextPaint.setColor(Color.parseColor("#878787"));

        // 连接线条
        linePaint = new Paint();
        linePaint.setAntiAlias(true);
        linePaint.setStyle(Paint.Style.STROKE);
        linePaint.setStrokeWidth(mStrokeWidth);

        // 小圆点内环
        innerCirclePaint = new Paint();
        innerCirclePaint.setStyle(Paint.Style.FILL);
        innerCirclePaint.setAntiAlias(true);
        innerCirclePaint.setColor(Color.WHITE);
        innerCirclePaint.setStrokeWidth(ComUtil.dip2px(context, 4));


        // 折线路径
        mpolylinePath = new Path();

        //小圆点外环半径
        outerRadius = ComUtil.dip2px(context, 4);
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        myInterval = (getHeight() - mBottomInterval - mTopInterval) / (dividerCount + 1);
        Log.e(TAG, "myInterval:" + myInterval);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
        Log.d(TAG, "widthSize:" + widthSize + ",heightSize:" + heightSize);
        mHeight = heightSize;
        if (mXAxis == null) {
            setMeasuredDimension(widthMeasureSpec, heightMeasureSpec);
            Log.d(TAG, "mWidth:" + mWidth + ",mHeight:" + mHeight + "mXAxis:" + mXAxis);
            return;
        }
        //宽度通过数组长度计算
//        mWidth = mxInterval * (mXAxis.size() - 1) + mLeftInterval * 2;
        mWidth = widthSize;

        mxInterval = (mWidth / (mYAxisList.get(0).size() + 1));
        yTextPaint.getTextBounds(String.valueOf(maxYValue), 0, String.valueOf(maxYValue).length(), yTextRect);
        startDrawX = yTextRect.width();
        mLeftInterval = initLeftInterval + startDrawX;
        setMeasuredDimension(mWidth, mHeight);
    }


    @Override
    protected void onDraw(Canvas canvas) {
        if (mXAxis == null || mYAxisList == null) {
            Log.e(TAG, "数据异常");
            return;
        }
        double maxYName = Math.ceil(maxYValue);
        int midNum = myLineNum - 1;
        //y轴刻度线
        String mYText = "";
        for (int i = 0; i < myLineNum; i++) {
            canvas.save();
            double midScore = maxYName / midNum * i;
            if (i == midNum) {
                mYText = String.valueOf((int) maxYName);
            } else {
                mYText = String.valueOf((int) midScore);
            }
            canvas.drawText(mYText, startDrawX, mHeight - mBottomInterval - i * myInterval + yTextRect.height() / 2, yTextPaint);
        }

        /**
         * 画标签
         */
        Paint bigCirPaint = new Paint();
        bigCirPaint.setAntiAlias(true);
        int off_width = 0;
        for (int i = mLabels.size() - 1; i >= 0; i--) {
            bigCirPaint.setColor(colorArray[i % colorArray.length]);
            String text = mLabels.get(i);
            Rect rect = new Rect();
            yTextPaint.getTextBounds(text, 0, text.length(), rect);
            LogUtils.i("rect width:" + rect.width());
            off_width = off_width + rect.width() + mLabelInterval;
            canvas.drawText(text, mWidth - mRightInterval - mLeftInterval - off_width, mHeight - mBottomInterval - 10 * myInterval - 2 * yTextRect.height(), yTextPaint);
            off_width = off_width + mLabelInterval * 2;
            canvas.drawCircle(mWidth - mRightInterval - mLeftInterval - off_width, mHeight - mBottomInterval - 10 * myInterval - 2 * yTextRect.height() - yTextRect.height() / 2, outerRadius, bigCirPaint);
        }


        // 画横线
        for (int i = 0; i <= dividerCount; i++) {
            canvas.drawLine(mLeftInterval, mHeight - mBottomInterval - i * myInterval, mXAxis.size() * mxInterval + mLeftInterval,
                    mHeight - mBottomInterval - myInterval * i, yTextPaint);
        }


        canvas.drawText("得分率(%)", mLeftInterval, mHeight - mBottomInterval - 10 * myInterval - 2 * yTextRect.height(), yTextPaint);


        // x轴的刻度集合
        int[] xPoints = new int[mXAxis.size()];
        for (int i = 0; i < mXAxis.size(); i++) {
            float xTextWidth = axisPaint.measureText(mXAxis.get(i)) / 2; //文字宽度一半
            float xfloat = (i + 1) * mxInterval + mLeftInterval - xTextWidth;
            // 画X轴的文字
            canvas.drawText(mXAxis.get(i), xfloat, mHeight - mBottomInterval + mYAxisFontSize, axisTextPaint);
            xPoints[i] = (int) (xfloat + xTextWidth);

            // 画竖线
            float xvfloat = i * mxInterval + mLeftInterval;
            canvas.drawLine(xvfloat, mHeight - mBottomInterval, xvfloat,
                    mHeight - mBottomInterval - myInterval * dividerCount, yTextPaint);
        }
        //最后一根竖线
        float xLastFloat = mXAxis.size() * mxInterval + mLeftInterval;
        canvas.drawLine(xLastFloat, mHeight - mBottomInterval, xLastFloat,
                mHeight - mBottomInterval - myInterval * dividerCount, yTextPaint);

        /**
         * 画轨迹
         * 分隔数量10，不需要减一
         */
        int y = myInterval * (dividerCount); // 只拿纵轴的dividerCount-1/dividerCount画图
//        axisPaint.setColor(mLineColor); // 设置坐标值的颜色
        for (int k = 0; k < mYAxisList.size(); k++) {
            Log.e(TAG, "color index:" + k % colorArray.length);
            innerCirclePaint.setColor(colorArray[k % colorArray.length]);
            linePaint.setColor(colorArray[k % colorArray.length]);
            numPaint.setColor(colorArray[k % colorArray.length]);

            ArrayList<Float> mYAxis = mYAxisList.get(k);
            mpolylinePath.reset();


            for (int i = 0; i < mYAxis.size(); i++) {
                int h = (int) (mHeight - (mBottomInterval + y * mYAxis.get(i) / maxYValue));
                float textWidth = axisPaint.measureText(String.valueOf(mYAxis.get(i))) / 2; //文字宽度一半
                float ay;
                if (mYAxis.get(i)==0){
                    ay = h - mYAxisFontSize;
                }else{
                    ay = h - direct[k % direct.length] * mYAxisFontSize;
                }

                if (i == 0) {
                    mpolylinePath.moveTo(mxInterval + mLeftInterval, h);
                    canvas.drawText(String.format("%.1f", mYAxis.get(i)), mxInterval + mLeftInterval - textWidth, ay, numPaint);
                } else {
                    mpolylinePath.lineTo(mLeftInterval + (i + 1) * mxInterval, h);
                    canvas.drawText(String.format("%.1f", mYAxis.get(i)), mLeftInterval + (i + 1) * mxInterval - textWidth, ay, numPaint);
                }
            }

            canvas.drawPath(mpolylinePath, linePaint);



            /**
             * 画小圆圈
             */
            for (int i = 0; i < mYAxis.size(); i++) {
                int h = (int) (mHeight - (mBottomInterval + y * mYAxis.get(i) / maxYValue));
                if (i == 0) {
                    canvas.drawCircle(mxInterval + mLeftInterval, h, outerRadius, innerCirclePaint);
                } else {
                    canvas.drawCircle(mLeftInterval + (i + 1) * mxInterval, h, outerRadius, innerCirclePaint);
                }
            }

        }


    }

    /**
     * 设置Y轴文字
     *
     * @param yItem
     */
    public void setYItem(ArrayList<ArrayList<Float>> yItem) {
        mYAxisList = yItem;
    }

    /**
     * 设置X轴文字
     *
     * @param xItem
     */
    public void setXItem(ArrayList xItem) {
        mXAxis = xItem;
    }


    public void setMaxYValue(int maxYValue) {
        this.maxYValue = maxYValue;
        invalidate();
    }

    public void setLabel(ArrayList labels) {
        mLabels = labels;
    }
}
